<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Code;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ResetController extends Controller
{
    public function sendCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'device' => 'required',
            'type' => Rule::in([1, 2]),
        ], [
            'device.required' => '设备不能为空',
            'type.in' => '类型不合法',
        ]);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }
        $type = $request->get('type');
        switch ($type) {
            case 1: {
                $validator = Validator::make($request->all(), [
                    'device' => 'email'
                ], [
                    'device.email' => '邮箱不合法'
                ]);
                if ($validator->fails()) {
                    return jsonResponse(config('common.validatorError'), $validator);
                }
                $device = $request->get('device');
                $number = rand(100000, 999999);
                // 第一个参数为邮件模板，第二个为模板上需要的参数，第三个为回调函数
                Mail::send('email', ['code' => $number], function($message) use ($device){
                    $message->to($device)->subject('ShopMx-验证码');  // subject为邮件主题
                });
                $code = Code::where('device', $device)->first();
                if (empty($code)) {
                    $code = new Code();
                    $code['device'] = $device;
                }
                $code['code'] = $number;
                $code->save();
                break;
            }
            case 2: {
                $device = $request->get('device');
                break;
            }
            default: {
                return jsonResponse(40001);
            }
        }
        return jsonResponse(config('common.successCode'));
    }
}
